Hot100(golang)
Leetcode
Hot100
Golang
-image.png)
记录一下经典leetcode hot100的解题思路和题解
哈希
1. 两数之和
题解
package main
import (
"fmt"
"reflect"
)
func twoSum(nums []int, target int) (ans []int) {
mp := map[int]int{}
for idx, num := range nums {
if i, ok := mp[target-num]; ok {
ans = []int{i, idx}
}
mp[num] = idx
}
return ans
}
func main() {
testCases := []struct {
nums []int
target int
ans []int
}{
{nums: []int{2, 7, 11, 15}, target: 9, ans: []int{0, 1}},
{nums: []int{3, 2, 4}, target: 6, ans: []int{1, 2}},
{nums: []int{3, 3}, target: 6, ans: []int{0, 1}},
}
for _, t := range testCases {
fmt.Println(reflect.DeepEqual(twoSum(t.nums, t.target), t.ans))
}
}-image-1.png)
-image-5.png)
49. 字母异位词分组
题解
package main
import (
"fmt"
"reflect"
"slices"
)
func groupAnagrams(strs []string) [][]string {
mp := map[string][]string{}
for _, str := range strs {
s := []byte(str)
slices.Sort(s)
mp[string(s)] = append(mp[string(s)], str)
}
ans := make([][]string, 0, len(mp))
for i := range mp {
ans = append(ans, mp[i])
}
return ans
}
func main() {
testCases := []struct {
strs []string
ans [][]string
}{
{
[]string{"eat", "tea", "tan", "ate", "nat", "bat"},
[][]string{
{"eat", "tea", "ate"},
{"tan", "nat"},
{"bat"},
},
},
{
[]string{""},
[][]string{
{""},
},
},
{
[]string{"a"},
[][]string{
{"a"},
},
},
}
for _, t := range testCases {
fmt.Println(reflect.DeepEqual(groupAnagrams(t.strs), t.ans))
}
}-image-6.png)
-image-4.png)
128. 最长连续序列
题解
package main
import "fmt"
func longestConsecutive(nums []int) int {
ans := 0
mp := map[int]bool{}
for _, num := range nums {
mp[num] = true
}
for i := range mp {
if mp[i-1] == true {
continue
}
cnt := 1
for mp[i+1] == true {
i += 1
cnt += 1
}
ans = max(ans, cnt)
}
return ans
}
func main() {
testCases := []struct {
nums []int
ans int
}{
{[]int{100, 4, 200, 1, 3, 2}, 4},
{[]int{0, 3, 7, 2, 5, 8, 4, 6, 0, 1}, 9},
{[]int{1, 0, 1, 2}, 3},
}
for _, t := range testCases {
fmt.Println(longestConsecutive(t.nums) == t.ans)
}
}-image-2.png)
-image-3.png)